import React, { Component } from 'react';
import { GLOBAL } from '../../../config/global';
import {
  StyleSheet,
  Text,
  View,
  Image,
  TouchableOpacity,
  PixelRatio,
  TextInput,
  FlatList,
  Alert
} from "react-native";
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { ApprovalView, RefuseModal } from '../../../component/ModalVerifylComponent.js';
import { Right } from 'native-base';
import Toast from 'react-native-root-toast';
import Dictionary from '../../../utils/dictionary';
import HTTP from '../../../utils/http';
import { API, API_GENERATE } from '../../../config/api';
import ToastUtil from '../../../utils/toast';
import { CalendarList } from 'react-native-calendars';
import { RangTime } from '../../../component/common/RangTime.js';
import MethodUtil from '../../../utils/MethodUtil';

const scale = GLOBAL.SCALE;
const searchIcon = require('../../../imgs/global/whiteSearch.png');
const arrowIcon = require('../../../imgs/select.png');

export class ClaimListPage extends Component {

  static navigationOptions = ({ navigation, navigationOptions }) => {
    const params = navigation.state.params || {};
    // listType   'A' -> 申领列表  'E' -> 审批列表  (默认显示审批列表)
    let title = params.listType == 'A' ? '企业认领申请列表' : '企业认领审批列表';
    return {
      title,
      headerTintColor: '#fff',
      headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
      headerStyle: style.head.headerStyle,
    }
  }

  constructor(props) {
    super(props);
    let { listType, status, choice } = props.navigation.state.params || {};

    this.state = {
      status: 'data',
      showSelect: false,
      selectIndex: 0,
      statusText: '全部',
      statusId: '1',
      listData: [],
      applyStatusList: [{
        title: '全部',
        dickKey: status || ''
      }],
      refreshIcon: false, // 下拉刷新图标
      showRejectModal: false,
      showTimeModal: false,
      timeDay: null,
      choice: choice || {}
    }
    this.listType = listType || 'E';
    this.onRefresh = true; // 判断是整个页面刷新还是下拉刷新
    this.totalPage = 1;
    this.pageParams = {
      pageNo: 1,
      pageSize: 10,
      searchCode: '',
      status: status || '',
      startDate: '',
      endDate: '',
      corpId: choice.corpId || ''
    }
    this.selectedItem = {
      formKey: '',
      taskId: '',
      businessKey: ''
    }
  }

  async componentWillMount () {
    await this.getDictionary();
    this.initPage();
  }

  initPage = async () => {
    this.setState({
      status: this.onRefresh ? 'loading' : 'data',
      refreshIcon: !this.onRefresh && this.pageParams.pageNo == '1'
    })
    let URL = this.listType == 'A' ? API.ENTERPRISE_CLAIM_LIST : API.ENTERPRISE_CLAIM_AUDIT_LIST;
    let res = await HTTP.POST(API_GENERATE(URL), this.pageParams);
    if (res) {
      this.totalPage = res.totalPage;
      this.setState({
        status: res.rows.length > 0 ? 'data' : 'empty',
        listData: this.pageParams.pageNo == '1' ? res.rows : this.state.listData.concat(res.rows),
        refreshIcon: false
      })
    } else {
      this.setState({
        refreshIcon: false,
        status: 'error'
      })
    }
  }

  getDictionary = async () => {
    let { status } = this.props.navigation.state.params;
    let res = await Dictionary.get('CC_STAFF_COMPANY_APPLY_STATUS');
    res.map((item, index) => {
      item.title = item.dictName;
      if (status && item.dictKey == status) {
        let res = { index: index + 1, item }
        this.changeStatus(res);
      }
    })

    this.setState({
      applyStatusList: this.state.applyStatusList.concat(res)
    })
  }


  // 切换筛选状态
  changeStatus = (res) => {
    if (res) {
      this.pageParams.status = res.item.dictKey || '';
      this.pageParams.pageNo = 1;
      this.setState({
        showSelect: false,
        selectIndex: res.index,
        statusText: res.item.title,
      }, () => {
        this.refresh();
      })
    }
  }

  toggleSelect = () => {
    this.setState({
      showSelect: !this.state.showSelect
    })
  }

  // 跳转企业认领页面
  goClaimPage = () => {
    this.props.navigation.navigate('EnterpriseClaimPage', {
      callBack: (data) => {
        if (data.success) {
          this.refresh();
        }
      },
      choice: this.state.choice
    })
  }




  _resultCall = (resultData) => {
    this.pageParams.startDate = resultData.startTime || '';
    this.pageParams.endDate = resultData.endTime || '';
    this.setState({
      showTimeModal: false
    }, () => {
      this.refresh()
    })
  }

  _renderSearchWrap = () => {
    return (
      <View style={styles.searchWrap}>

        <Image source={searchIcon} style={[styles.searchIcon, this.listType == 'E' ? { left: 104 * scale } : '']} />

        <TextInput
          ref="enterpriseInput"
          style={[styles.searchInput, this.listType == 'A' ? '' : { width: 329 * scale, paddingLeft: 120 * scale }]}
          underlineColorAndroid='transparent'
          placeholder={"请输入企业名称"}
          placeholderTextColor="#FFF"
          maxLength={30}
          returnKeyType={'search'}
          defaultValue={this.pageParams.searchCode}
          onChangeText={(txt) => { this.pageParams.searchCode = txt; }}
          onSubmitEditing={() => { this.refresh() }}
        />

        {
          this.listType == 'A' ? (
            <TouchableOpacity style={styles.claimBtn} onPress={() => { this.goClaimPage() }}>
              <Text style={styles.claimText}>企业认领</Text>
            </TouchableOpacity>
          ) : null
        }
      </View>
    )
  }

  renderFilterWrap = () => {
    let { statusText } = this.state;
    let { startDate, endDate } = this.pageParams;
    return (
      <View style={styles.filterWrap}>
        <TouchableOpacity style={styles.statusWrap} onPress={() => { this.toggleSelect() }}>
          {
            this.listType == 'A' ? (
              <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                <Text style={styles.statusBtn}>{statusText}</Text>
                <Image source={arrowIcon} style={styles.arrowIcon} />
              </View>) : null
          }
        </TouchableOpacity>


        <TouchableOpacity style={styles.statusWrap} onPress={() => {
          this.setState({
            showTimeModal: !this.state.showTimeModal,
            showSelect: false,
          })
        }}>
          <Text>{startDate || '开始时间'}/{endDate || '结束时间'}</Text>
        </TouchableOpacity>
      </View>
    )
  }

  _renderListItem = (item) => {
    item = item.item
    let approveInfo = item;
    if (this.listType == 'E') {
      item = item.applyDetailInfo
    }
    return (
      <View>
        <Text style={{ fontSize: 12 * scale, textAlign: 'right', marginBottom: 6 * scale }}>{item.createTime || '--'}</Text>
        <View style={styles.listItem}>
          <View style={styles.userWrap}>
            <TouchableOpacity style={styles.userInfo} onPress={() => {
              this.props.navigation.navigate('EnterpriseDetailsPage', {
                companyId: item.companyId,
                title: item.companyName,
                status: "PASS",
                menuKey: 'info',
                choice: this.state.choice
              })
            }}>
              <Text numberOfLines={1} style={{ fontSize: 12 * scale, color: style.color.themeColor, }}>{item.companyName || '--'}</Text>
            </TouchableOpacity>
          </View>
          <View style={styles.flexBox}>
            <Text style={{ fontSize: 12 * scale, color: '#000', opacity: 0.8, flexDirection: 'row', }}>{item.createByName || '--'} | {item.bizTeamName || '--'} ({item.organName || '--'})</Text>
          </View>
          <View style={styles.applyInfo}>
            <View style={[{ width: 200 * scale }, this.listType == 'E' ? { width: 250 * scale } : '']}>
              <View style={{ flexDirection: 'row', alignItems: 'flex-start', }}>
                <Text style={styles.reasonText}>申请理由：</Text>
                <Text style={styles.reasonText}>{item.comments || '--'}</Text>
              </View>
              {
                this.listType == 'A' && item.auditRemark ? (<View style={{ marginTop: 12 * scale, flexDirection: 'row', alignItems: 'center' }}>
                  <Text style={styles.reasonText}>驳回原因：</Text>
                  <Text style={styles.reasonText}>{item.auditRemark || '--'}</Text>
                </View>) : null
              }
            </View>
            {/* 申请列表状态 */}
            {
              this.listType == 'A' ? <Text style={styles.statusText}>{item.statusName || '--'}</Text> : null
            }
          </View>
          {/* 审批列表操作项 */}
          {
            this.listType == 'E' ? (<View style={styles.operation}>
              <TouchableOpacity style={[styles.btn, styles.passBtn]} onPress={() => {
                this.passConfirm(approveInfo.taskId, approveInfo.formKey, item.applyId);
              }}>
                <Text style={{ fontSize: 12 * scale, color: '#fff' }}>通过</Text>
              </TouchableOpacity>
              <TouchableOpacity style={[styles.btn, styles.rejectBtn]} onPress={() => {
                this.setState({
                  showRejectModal: true
                }, () => {
                  this.selectedItem.taskId = approveInfo.taskId;
                  this.selectedItem.formKey = approveInfo.formKey;
                  this.selectedItem.businessKey = item.applyId;
                })
              }}>
                <Text style={{ fontSize: 12 * scale, color: style.color.themeColor }}>驳回</Text>
              </TouchableOpacity>
            </View>) : null
          }
        </View>
      </View>
    )
  }

  // 审批-通过
  passConfirm = (taskId, formKey, businessKey) => {
    Alert.alert(
      '提示',
      `是否确认通过审批？`,
      [
        { text: '取消', },
        {
          text: '确认', onPress: async () => {
            this.setState({
              status: 'loading'
            })
            let res = await HTTP.POST(API_GENERATE(API.ENTERPRISE_CLAIM_AUDIT), {
              auditResult: '1',
              taskId,
              formKey,
              businessKey,
            });
            if (res) {
              ToastUtil.showSuccess('审批成功').then(() => { this.refresh() })
            } else {
              this.setState({
                status: 'data'
              })
            }
          }
        },
      ],
    )
  }

  // 审批-驳回
  rejectConfirm = async (remark) => {
    if (remark) {
      let { taskId, formKey, businessKey } = this.selectedItem;
      this.setState({
        showRejectModal: false,
        status: 'loading'
      });
      let res = await HTTP.POST(API_GENERATE(API.ENTERPRISE_CLAIM_AUDIT), {
        auditResult: '0',
        remark,
        taskId,
        formKey,
        businessKey,
      });
      if (res) {
        ToastUtil.showSuccess('审批驳回成功').then(() => { this.refresh() })
      } else {
        this.setState({
          status: 'data'
        })
      }
    } else {
      ToastUtil.showWarning('请输入驳回原因');
    }
  }

  // 下拉刷新
  refresh = () => {
    this.pageParams.pageNo = 1;
    this.onRefresh = false;
    this.initPage();
  }

  // 加载更多
  loadMore = () => {
    if (this.totalPage > this.pageParams.pageNo) {
      this.pageParams.pageNo++;
      this.onRefresh = false;
      this.initPage();
    }
  }

  onErrorRefresh = () => {
    this.pageParams.pageNo = 1;
    this.onRefresh = true;
    this.initPage();
  }

  render () {
    let { showSelect, selectIndex, statusText, status, refreshIcon, listData, showRejectModal, applyStatusList, showTimeModal, timeDay } = this.state;
    return (
      <View style={styles.container}>
        {/* 搜索 */}
        {this._renderSearchWrap()}

        {/* 过滤条件 */}
        {this.renderFilterWrap()}


        {
          status == 'data' ? (<View style={styles.listWrap}>
            <FlatList
              data={listData}
              renderItem={this._renderListItem}
              refreshing={refreshIcon}
              onRefresh={() => { this.refresh() }}
              onEndReachedThreshold={0.1}
              onEndReached={() => { this.loadMore() }}
            />
          </View>) : null
        }

        {
          showTimeModal ? <RangTime isVisible={true} markedDates={null} startTime={this.pageParams.startDate} endTime={this.pageParams.endDate} resultCall={this._resultCall} /> : null
        }


        {this.listType == 'A' && showSelect ? (<Common data={applyStatusList} itemFn={this.changeStatus} imgIndex={selectIndex} allClick={this.toggleSelect} styleOut={{ marginTop: 120 * scale }} type="selectModal" />) : null}

        {
          status != 'data' ? (<PageStatusIndex status={status} emptyText="暂无记录" onErrorPress={this.onErrorRefresh} />) : null
        }

        {
          this.listType == 'E' ? (<RefuseModal visible={showRejectModal}
            placeholderText={'请输入驳回原因'}
            titleText={'驳回原因'}
            btnPress={(text) => {
              this.rejectConfirm(text);
            }}
            bgPress={() => {
              this.setState({
                showRejectModal: false,
              });
            }} />) : null
        }
      </View >
    )
  }
}

const styles = StyleSheet.create({
  searchWrap: {
    height: 66 * scale,
    paddingLeft: 12 * scale,
    paddingRight: 12 * scale,
    backgroundColor: style.color.themeColor,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    position: 'relative',
  },
  searchInput: {
    backgroundColor: '#5DA0FC',
    borderRadius: 6 * scale,
    height: 36 * scale,
    width: 268 * scale,
    marginRight: 12 * scale,
    color: '#fff',
    paddingLeft: 86 * scale,
    paddingRight: 10 * scale,
    paddingVertical: 0,
  },
  searchIcon: {
    width: 20 * scale,
    height: 20 * scale,
    position: 'absolute',
    left: 66 * scale,
    top: 23 * scale,
    zIndex: 9,
    opacity: 0.8,
  },
  claimBtn: {
    height: 36 * scale,
    backgroundColor: '#fff',
    width: 70 * scale,
    borderRadius: 8 * scale,
    alignItems: 'center',
    justifyContent: 'center',
  },
  claimText: {
    color: style.color.themeColor,
    fontSize: 12 * scale,
  },
  container: {
    backgroundColor: '#F0F4FD',
    flex: 1
  },
  filterWrap: {
    height: 56 * scale,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingLeft: 23 * scale,
    paddingRight: 23 * scale,
  },
  statusWrap: {
    flexDirection: 'row',
    alignItems: 'center',
    height: 56 * scale,
  },
  statusBtn: {
    color: style.color.themeColor,
    marginRight: 10 * scale,
  },
  listWrap: {
    paddingLeft: 12 * scale,
    paddingRight: 12 * scale,
    height: '100%',
    paddingBottom: 116 * scale,
  },
  listItem: {
    backgroundColor: '#fff',
    borderRadius: 6 * scale,
    marginBottom: 18 * scale,
  },
  userWrap: {
    flexDirection: 'row',
    alignItems: 'center',
    // justifyContent: 'space-between',
    paddingTop: 12 * scale,
    paddingLeft: 12 * scale,
    paddingRight: 12 * scale,
    paddingBottom: 12 * scale,
    borderBottomWidth: 1 / PixelRatio.get(),
    borderStyle: 'solid',
    borderColor: '#E3E7F0',
  },
  flexBox: {
    flexDirection: 'row',
    paddingLeft: 12 * scale,
    paddingRight: 12 * scale,
    paddingTop: 5 * scale,
  },
  userInfo: {
    flexDirection: 'row',
    // alignItems: 'center',
    // height: 36 * scale,
    width: '100%'
  },
  applyInfo: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingLeft: 12 * scale,
    paddingRight: 20 * scale,
    paddingTop: 16 * scale,
    paddingBottom: 16 * scale,
  },
  statusText: {
    color: '#000',
    fontSize: 12 * scale,
    width: 60 * scale,
    textAlign: 'right',
  },
  reasonText: {
    fontSize: 12 * scale,
    color: '#000',
    lineHeight: 18 * scale
  },
  operation: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
    marginBottom: 18 * scale,
    marginRight: 12 * scale,
  },
  btn: {
    width: 66 * scale,
    height: 28 * scale,
    borderRadius: 6 * scale,
    borderWidth: 1 / PixelRatio.get(),
    borderStyle: 'solid',
    borderColor: style.color.themeColor,
    justifyContent: 'center',
    alignItems: 'center',
  },
  passBtn: {
    backgroundColor: style.color.themeColor,
  },
  rejectBtn: {
    backgroundColor: '#fff',
    marginLeft: 14 * scale
  }
})